package atag.gui;
import java.net.*;
import java.io.*;

public class Transmitter {

  public boolean timedOut = false;

  public Transmitter() {
    boolean exists = (new File("C:\\ATaG-Demo\\SensorReadings\\Temperature")).exists();
    if (!exists)
      (new File("C:\\ATaG-Demo\\SensorReadings\\Temperature")).mkdirs();
    exists = (new File("C:\\ATaG-Demo\\SensorReadings\\Sound")).exists();
    if (!exists)
      (new File("C:\\ATaG-Demo\\SensorReadings\\Sound")).mkdirs();
  }

  public void transmitSensorReading(int sensorType, int newReading, int nodeID) {
    String dirName;
    if (sensorType==Constants.ACOUSTIC_SENSOR)
      dirName = "C:\\ATaG-Demo\\SensorReadings\\Sound\\";
    else
      dirName = "C:\\ATaG-Demo\\SensorReadings\\Temperature\\";

    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(dirName+nodeID+".txt"));
        out.write(Integer.toString(newReading));
        out.close();
    } catch (IOException e) {
    }

    return;
  }

  public void transmitSensorReadingx(int sensorType, int newReading, int nodeID) {
    //System.out.println("Attempting to send new reading " + newReading + " for sensor type " + sensorType + " for node " + nodeID);

    SensorReading msg = new SensorReading(newReading);
    Socket socket = null;
    int attempt = 0;
    int port;
    if (sensorType == Constants.TEMPERATURE_SENSOR)
      port = Constants.TEMPERATURE_SENSOR_READINGS_BASE_PORT + nodeID;
    else
      port = Constants.ACOUSTIC_SENSOR_READINGS_BASE_PORT + nodeID;

    for (attempt = 0; attempt < 2; attempt++) {
      try {
        //viz_ia = InetAddress.getByName("narmada.usc.edu");
        //viz_socket = new Socket(viz_ia, VIZ_PORT);
        socket = new Socket("localhost", port);
        break;
      }
      catch (UnknownHostException ex) {
        System.out.println("Unknown host exception");
        return;
      }
      catch (IOException ex) {
        System.out.println("Attempt " + attempt + ": Listener not initialized");
        try {
          Thread.sleep(2000);
        }
        catch (InterruptedException e) {
          System.out.println("Sleep interrupted. What's up?");
        }
      }
    }
    if (attempt == 5) {
      System.err.println("Cannot send new sensor reading to node " + nodeID);
      return;
    }

    System.out.println("Sending new reading to port " + port);
    ObjectOutputStream sr_oos = null;
    try {
      sr_oos = new ObjectOutputStream(socket.getOutputStream());
      sr_oos.writeObject(msg);
      sr_oos.flush();
      sr_oos.close();
      socket.close();
    }
    catch (IOException ex1) {
      System.out.println("Could not get output stream");
      System.exit( -1);
    }
  }
}
